const Service = require('egg').Service

module.exports = class zeroyuanBuy extends Service {
  async getGoodsList({ userId, pageSize, page, commodity_name, commodityid }) {
    const { ctx, service, logger, app } = this;
    try {
      let limit = [(page - 1) * pageSize, pageSize], res = {}, where = [];

      commodityid ? where.push(`commodityid=${commodityid}`) : (commodity_name ? where.push(`commodity_name='${commodity_name}'`) : '')

      res.list = await service.common.findAll({
        tableName: 'hd_commodity',
        filed: [
          'commodityid', 'ccolumnid', 'commodity_name', 'commodity_desc', 'label_name', 'reason',
          'market_price',
          'productid',
          'invest_money',
          'invest_not_full_num',
          'invest_full_num',
          'sale_money',
          'c_by',
          'u_by',
          `DATE_FORMAT(u_time ,'%Y/%m/%d:%H:%i:%S') as update_time`,
          `DATE_FORMAT(c_time ,'%Y/%m/%d:%H:%i:%S') as create_time`,
        ],
        where: `${where.join(' AND ')}`,
        others: `ORDER BY c_time DESC LIMIT ${limit.join(',')}`
      })

      res.total = (await service.common.findOne({
        tableName: 'hd_commodity',
        filed: ['COUNT(*) as num'],
        where: where.join(' AND ')
      })).num

      return {
        code: 10200,
        data: res,
        msg: '请求成功！'
      }

    } catch (error) {

    }
  }

  async getPhoto({ userId, commodityid }) {
    const { ctx, service } = this;
    try {
      let photo_path = {}
      let phones = await service.common.findAll({
        tableName: 'hd_commodity_photo',
        where: { commodityid }
      });
      if (phones instanceof Array) {
        phones.forEach(item => {
          photo_path[`photo_path${item.photo_type}`] = item.photo_path
        })
      }
      return {
        code: 10200,
        data: photo_path,
        msg: "success"
      }

    } catch (error) {
      return {
        code: 10500,
        msg: '系统异常'
      }
    }
  }

  async addGoods(params) {
    const { app, ctx, service } = this;
    let {
      userId,
      ccolumnid,
      commodity_name,
      commodity_desc,
      label_name,
      reason,
      market_price,
      productid,
      invest_money,
      sale_money,
      obtain_way,
      photo_path1,
      photo_path2
    } = params

    // 商品名称不能重复
    let _goods = await service.common.findOne({
      tableName: 'hd_commodity',
      where: {
        commodity_name: `'${commodity_name}'`,
      }
    })
    if (_goods) {
      return {
        code: 10101,
        msg: '商品名称重复'
      }
    }
    // console.log('----11123123123123', _goods)

    let _params = {
      ccolumnid,
      commodity_name: commodity_name ? `'${commodity_name}'` : null,
      commodity_desc: commodity_desc ? `'${commodity_desc}'` : null,
      label_name: label_name ? `'${label_name}'` : null,
      reason: reason ? `'${reason}'` : null,
      market_price,
      productid,
      obtain_way,
      invest_money,
      sale_money,
      c_by: userId
    }

    for (let key in _params) {
      if (!_params[key]) {
        delete _params[key]
      }
    };

    let res = await service.common.insertOne({
      tableName: 'hd_commodity',
      params: _params,
    })

    console.log(res, '-83942934892348-res');
    let commodityid = res[0];

    if (!commodityid) {
      return {
        code: 10101,
        msg: "商品创建失败"
      }
    }

    await service.common.insertOne({
      tableName: 'hd_commodity_photo',
      params: {
        commodityid,
        photo_type: 1,
        photo_path: `'${photo_path1}'`
      }
    })

    await service.common.insertOne({
      tableName: 'hd_commodity_photo',
      params: {
        commodityid,
        photo_type: 2,
        photo_path: `'${photo_path2}'`
      }
    })
    return {
      code: 10200,
      msg: "创建成功"
    }
  }
  async upDataGoods(params) {
    const { app, service } = this;
    try {
      let {
        commodityid,
        userId,
        ccolumnid,
        commodity_name,
        commodity_desc,
        label_name,
        reason,
        market_price,
        productid,
        invest_money,
        sale_money,
        obtain_way,
        // cphotoid,
        // photo_path,
        photo_path2,
        photo_path1,
        operationType
      } = params

      if (operationType === 'del') {
        await service.common.del({
          tableName: 'hd_commodity',
          where: {
            commodityid,
          }
        })
        // if (cphotoid) {
        //   await service.common.del({
        //     tableName: 'hd_commodity_photo',
        //     where: {
        //       cphotoid,
        //       commodityid,
        //     }
        //   })
        // }
      }
      let _params = {
        ccolumnid,
        commodity_name: commodity_name ? `'${commodity_name}'` : null,
        commodity_desc: commodity_desc ? `'${commodity_desc}'` : null,
        label_name: label_name ? `'${label_name}'` : null,
        reason: reason ? `'${reason}'` : null,
        market_price,
        obtain_way,
        productid,
        invest_money,
        sale_money,
        u_by: userId
      }
      for (let key in _params) {
        if (!_params[key]) {
          delete _params[key]
        }
      };

      await service.common.upData({
        tableName: 'hd_commodity',
        value: _params,
        where: {
          commodityid,
        }
      })
      // if (cphotoid) {
      if (photo_path2) {
        await service.common.upData({ // 更新详情
          tableName: 'hd_commodity_photo',
          value: {
            photo_path: `'${photo_path2}'`
          },
          where: {
            commodityid,
            photo_type: 2
          }
        })

      }

      if (photo_path1) {
        await service.common.upData({ // 更新展示图
          tableName: 'hd_commodity_photo',
          value: {
            photo_path: `'${photo_path1}'`
          },
          where: {
            commodityid,
            photo_type: 1
          }
        })
      }
      console.log('------asdfasdfasdfasdfasdf', photo_path2, photo_path1)
      // }
      return {
        code: 10200,
        msg: '更新成功'
      }

    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '系统异常'
      }
    }
  }
  async addActive(params) {
    const { ctx, service } = this;
    try {
      let { channels, start_time, end_time, userId } = params
      let _channels = JSON.parse(channels)
      for (let item of _channels) {
        item.value = [start_time, end_time]
      }
      params.channels = JSON.stringify(_channels)
      // console.log('%c gc_params=>: ', 'color: MidnightBlue; background: Aquamarine; font-size: 20px;', params);
      params.is_old_data = 3;
      let result = await service.admin.active.addActive(params)
      if (!(result instanceof Array)) {
        return {
          code: 10101,
          msg: '添加失败'
        }
      }
      for (let item of result) {
        let _params = {
          combination_id: item.combinationId,
          commodityid: item.goodsId,
          is_display: 1,
          is_online: 1,
          is_top: 0,
          c_by: userId
        }
        await service.common.insertOne({
          tableName: 'hd_combination_relation_commodity',
          params: _params
        })
      }
      console.log(result, '----------result--------')
      return {
        code: 10200,
        msg: '创建成功'
      }
    } catch (error) {
      return {
        code: 10500,
        msg: '系统异常'
      }
    }
  }
  async getActiveList(params) {
    const { service } = this;
    params.is_old_data = 3
    return await service.admin.active.getActiveList(params);
  }

  // 获取零元购渠道
  async getChannels({ activeId, userId }) {
    const { service, ctx } = this;
    try {
      let channels = await service.common.findAll({
        sql: `
          SELECT hcrc.crcommodityid,hcrc.combination_id,hc.commodity_name,hc.commodityid,hch.name
          FROM hd_activity_base AS hcb
          LEFT JOIN hd_combination_relation as hcr ON hcb.id = hcr.activity_id
          LEFT JOIN hd_channel as hch ON hcr.channel_id=hch.id
          LEFT JOIN hd_combination_relation_commodity  hcrc  ON hcr.id=hcrc.combination_id
          LEFT JOIN hd_commodity as hc ON hcrc.commodityid=hc.commodityid
          WHERE hcb.id = ${activeId}
          ORDER BY hcrc.c_time
         `
      })
      return {
        code: 10200,
        data: channels,
        msg: 'success'
      }
    } catch (error) {
      console.log(error);
      return {
        code: 10500,
        msg: '系统异常'
      }
    }

  }

}